<?php
require_once '../../config/database.php';

// JSON 响应函数
function sendJson($data) {
    header('Content-Type: application/json; charset=utf-8');
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
    header('Access-Control-Allow-Headers: Content-Type, Authorization');
    
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
        exit;
    }
    
    echo json_encode($data, JSON_UNESCAPED_UNICODE);
    exit;
}

// 数据库连接
try {
    $pdo = new PDO(
        'mysql:host=' . DB_HOST . ';dbname=' . DB_NAME . ';charset=' . DB_CHARSET,
        DB_USER,
        DB_PASS,
        [
            PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
        ]
    );
} catch (PDOException $e) {
    sendJson([
        'code' => 500,
        'message' => '数据库连接失败',
        'data' => null
    ]);
}

$method = $_SERVER['REQUEST_METHOD'];
$action = $_GET['action'] ?? '';
$input = json_decode(file_get_contents('php://input'), true);

switch ($method) {
    case 'GET':
        if ($action == 'get_config') {
            try {
                // 获取4个配置项：包括富文本字段
                $stmt = $pdo->prepare("SELECT config_key, config_value FROM system_config WHERE config_key IN ('advance_booking_days', 'max_companions', 'reservation_notice', 'activity_notice')");
                $stmt->execute();
                $configs = $stmt->fetchAll();
                
                $result = [];
                foreach ($configs as $config) {
                    if (in_array($config['config_key'], ['advance_booking_days', 'max_companions'])) {
                        $result[$config['config_key']] = [
                            'value' => (int)$config['config_value'],
                            'type' => 'number'
                        ];
                    } else {
                        $result[$config['config_key']] = [
                            'value' => $config['config_value'],
                            'type' => 'string'
                        ];
                    }
                }
                
                // 如果没有配置，设置默认值
                if (!isset($result['advance_booking_days'])) {
                    $result['advance_booking_days'] = ['value' => 7, 'type' => 'number'];
                }
                if (!isset($result['max_companions'])) {
                    $result['max_companions'] = ['value' => 5, 'type' => 'number'];
                }
                if (!isset($result['reservation_notice'])) {
                    $result['reservation_notice'] = ['value' => '<p>预约须知：</p><ul><li>请按预约时间准时到达，逾期15分钟将自动取消预约</li><li>参观时请携带有效身份证件</li><li>14岁以下儿童须由成人陪同</li><li>参观过程中请保持安静，爱护展品</li><li>如需取消预约，请提前2小时操作</li></ul>', 'type' => 'string'];
                }
                if (!isset($result['activity_notice'])) {
                    $result['activity_notice'] = ['value' => '<p>活动申请说明：</p><ul><li>请提前至少7天提交活动申请</li><li>活动内容需符合校园文化建设要求</li><li>请详细填写活动信息和场地设备需求</li><li>我们将在3个工作日内完成审核并通知您</li><li>活动结束后请及时清理场地</li></ul>', 'type' => 'string'];
                }
                
                sendJson([
                    'code' => 200,
                    'message' => '获取成功',
                    'data' => $result
                ]);
            } catch (Exception $e) {
                sendJson([
                    'code' => 500,
                    'message' => '获取配置失败: ' . $e->getMessage(),
                    'data' => null
                ]);
            }
        } else {
            sendJson([
                'code' => 400,
                'message' => '无效的操作',
                'data' => null
            ]);
        }
        break;
        
    case 'POST':
        if ($action == 'update_config') {
            try {
                if (!isset($input['config_key']) || !isset($input['config_value'])) {
                    sendJson([
                        'code' => 400,
                        'message' => '缺少必要参数',
                        'data' => null
                    ]);
                }
                
                $configKey = $input['config_key'];
                $configValue = $input['config_value'];
                
                // 允许更新4个配置项
                if (!in_array($configKey, ['advance_booking_days', 'max_companions', 'reservation_notice', 'activity_notice'])) {
                    sendJson([
                        'code' => 400,
                        'message' => '不允许更新此配置项: ' . $configKey,
                        'data' => null
                    ]);
                }
                
                // 验证数值字段
                if (in_array($configKey, ['advance_booking_days', 'max_companions'])) {
                    if (!is_numeric($configValue) || $configValue < 1) {
                        sendJson([
                            'code' => 400,
                            'message' => '配置值必须是大于0的数字',
                            'data' => null
                        ]);
                    }
                }
                
                // 额外验证
                if ($configKey == 'advance_booking_days' && $configValue > 30) {
                    sendJson([
                        'code' => 400,
                        'message' => '可预约天数不能超过30天',
                        'data' => null
                    ]);
                }
                
                if ($configKey == 'max_companions' && $configValue > 10) {
                    sendJson([
                        'code' => 400,
                        'message' => '最大同行人数不能超过10人',
                        'data' => null
                    ]);
                }
                
                // 验证富文本字段长度
                if (in_array($configKey, ['reservation_notice', 'activity_notice'])) {
                    if (strlen($configValue) > 10000) {
                        sendJson([
                            'code' => 400,
                            'message' => '富文本内容长度不能超过10000字符',
                            'data' => null
                        ]);
                    }
                }
                
                // 检查配置是否存在
                $stmt = $pdo->prepare("SELECT id FROM system_config WHERE config_key = ?");
                $stmt->execute([$configKey]);
                $exists = $stmt->fetch();
                
                if ($exists) {
                    // 更新配置
                    $stmt = $pdo->prepare("UPDATE system_config SET config_value = ?, updated_at = NOW() WHERE config_key = ?");
                    $result = $stmt->execute([$configValue, $configKey]);
                } else {
                    // 插入新配置，根据配置类型设置描述
                    $descriptions = [
                        'advance_booking_days' => '可提前预约天数',
                        'max_companions' => '最大同行人数',
                        'reservation_notice' => '预约说明富文本内容',
                        'activity_notice' => '活动申请说明富文本内容'
                    ];
                    $description = $descriptions[$configKey] ?? $configKey;
                    
                    $stmt = $pdo->prepare("INSERT INTO system_config (config_key, config_value, config_desc, created_at, updated_at) VALUES (?, ?, ?, NOW(), NOW())");
                    $result = $stmt->execute([$configKey, $configValue, $description]);
                }
                
                if ($result) {
                    $returnValue = in_array($configKey, ['advance_booking_days', 'max_companions']) ? 
                        (int)$configValue : $configValue;
                        
                    sendJson([
                        'code' => 200,
                        'message' => '更新配置成功',
                        'data' => ['config_key' => $configKey, 'config_value' => $returnValue]
                    ]);
                } else {
                    sendJson([
                        'code' => 500,
                        'message' => '更新配置失败',
                        'data' => null
                    ]);
                }
            } catch (Exception $e) {
                sendJson([
                    'code' => 500,
                    'message' => '更新配置失败: ' . $e->getMessage(),
                    'data' => null
                ]);
            }
        } else {
            sendJson([
                'code' => 400,
                'message' => '无效的操作',
                'data' => null
            ]);
        }
        break;
        
    default:
        sendJson([
            'code' => 405,
            'message' => '不支持的请求方法',
            'data' => null
        ]);
}
?>